<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="资源名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="资源名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
				row-key="id"
				:tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="资源名称" prop="name" min-width="200"/>
        <el-table-column label="类型" prop="type"/>
        <!-- <el-table-column label="图标" prop="icon"/> -->
				<el-table-column label="地址" prop="url"/>
        <el-table-column label="路由标题（vue）" prop="title"/>
        <el-table-column label="组件路径（vue）" prop="component"/>
        <el-table-column label="排序数据" prop="sort"/>
        <el-table-column fixed="right" label="操作"  min-width="280" width="280">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openRoleDialog(scope.row)"
            ><i class="el-icon-set-up"></i> 分配角色</el-button>
            <el-button
              type="warning"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            ><i class="el-icon-edit"></i> 编辑</el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            ><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 资源表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="550px"
      :before-close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入资源名称" />
        </el-form-item>

        <el-form-item label="图标" prop="icon">
          <el-input v-model="formData.icon" placeholder="请输入资源图标" />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio label="MENU_URL">菜单资源</el-radio>
            <el-radio label="SERVICE_INTERFACE">接口资源</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="路径" prop="url">
          <el-input v-model="formData.url" placeholder="请输入资源路径" />
        </el-form-item>
        <el-form-item label="路由标题（vue）" prop="title">
          <el-input v-model="formData.title" placeholder="请输入路由标题" />
        </el-form-item>
				<el-form-item label="组件地址（vue）" prop="component">
          <el-input v-model="formData.component" placeholder="请输入组件地址" />
        </el-form-item>
        <el-form-item label="排序数字" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入排序数字" />
        </el-form-item>
				<div class="treeDiv">
					<div style="width: 50%; float: left; padding-left: 20px;">父级资源</div>
					<div style="width: 50%; float: left;">
						<el-tree
							:data="dataList"
							:props="defaultProps"
							accordion
							@node-click="handleNodeClick"
							ref="tree">
						</el-tree>
					</div>
				</div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配角色弹窗  -->
    <el-dialog
      :visible.sync="roleDialogVisible"
      :title="'【' + checkedResource.name + '】角色分配'"
      width="800px"
    >
      <el-scrollbar v-loading="loading" max-height="600px">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="roleList"
          highlight-current-row
          border
          @selection-change="handleSelectionRoleChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="角色名称" prop="zhCnName"/>
          <el-table-column label="角色标识" prop="enName"/>
        </el-table>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="allocateRoles">确 定</el-button>
          <el-button @click="closeRoleDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import userApi from '@/api/system/user'
import roleApi from '@/api/system/role'
import resourceApi from '@/api/system/resource'
export default {
	name: 'resourceIndex',
	data() {
		return {
			defaultProps: {
				children: 'children',
				label: 'name'
			},
			queryParams: {
        keywords: ''
      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      roleDialogVisible: false,
      roleList: [],
      checkedResource: {},
      dialog: {},
      formData: {},
      rules: {},

      sourceMap: {
        BUILT_IN: '系统内置',
        SYS_ADD: '系统添加',
        WX_LOGIN: '微信登录',
        PHONE_LOGIN: '手机号登录'
      },
      selectRoleIdArr: [],
			parentNode: {},
		};
	},
  methods: {
		handleNodeClick(val) {
			this.parentNode = val;
		},
    handleQuery() {
      this.loading = true;
      resourceApi.list().then((res) => {
        let data = res.data;
        this.dataList = data;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
			if (this.parentNode.id) {
				this.formData.parentId = this.parentNode.id;
			}
      if (this.formData.id) {
        resourceApi.update(this.formData).then((res) => {
          this.$message({message: '资源更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        resourceApi.add(this.formData).then((res) => {
          this.$message({message: '资源添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },

    openRoleDialog(row) {
      this.roleDialogVisible = true;
      this.checkedResource = row;
      
      roleApi.list().then((res) => {
        this.roleList = res.data;
        let that = this;
        this.$nextTick(function () {
					this.roleList.forEach((role) => {
						let resources = role.resources;
						let resourceIdArr = [];
						if (resources.length > 0) {
							resources.forEach((u) => {
								resourceIdArr.push(u.id);
							});
							if (resourceIdArr.indexOf(row.id) != -1) {
								that.$refs.multipleTable.toggleRowSelection(role, true);
							}
						}
				})})

      });
    },
    closeRoleDialog() {
      this.roleDialogVisible = false;
      this.roleList = [];
    },

    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      if (id) {
        this.$set(this.dialog, 'title', '编辑资源');
        resourceApi.get(id).then((res) => {
          let data = res.data;
          this.formData = data;
        });
      } else {
        this.$set(this.dialog, 'title', '新增资源');
        this.formData = {};
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        resourceApi.delete(id).then((res) => {
          this.$message({message: '资源删除成功！', type: 'success'});
          this.handleQuery();
        });
      } else {
        this.$message.error('暂不支持批量删除资源！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    allocateRoles() {
      let resourceId = this.checkedResource.id;
      let roleIdArr = this.selectRoleIdArr;
      resourceApi.allocateRoles(resourceId, roleIdArr).then((res) => {
        this.$message({message: '资源角色设置成功！', type: 'success'});
        this.closeRoleDialog();
      });
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>